import type { BasicTableProps } from '../types/table';
import type { PaginationProps } from '../types/pagination';
import { ref, ComputedRef, unref, computed, onMounted, watchEffect, watch } from 'vue';
import { isBoolean } from '@/utils/is';
import { table } from '@/conf/component';

const { apiSetting, defaultPage, defaultPageSize, pageSizes } = table;

export function useDataSource(
  propsRef: ComputedRef<BasicTableProps>,
  { getPaginationInfo, setPagination, setLoading, tableData }: any,
  emit: any
) {
  const dataSourceRef = ref([]);

  console.log('useDataSource.propsRef---->', propsRef);

  watchEffect(() => {
    tableData.value = unref(dataSourceRef);
  });

  watch(
    () => unref(propsRef).dataSource,
    () => {
      const { dataSource }: any = unref(propsRef);
      dataSource && (dataSourceRef.value = dataSource);
    },
    {
      immediate: true,
    }
  );

  const getRowKey = computed(() => {
    const { rowKey }: any = unref(propsRef);
    return rowKey ? (row: { [x: string]: any }) => row[rowKey] : () => 'rowKey';
  });

  const setTableData = (values: never[]) => {
    dataSourceRef.value = values;
  };

  const getDataSource = () => {
    return getDataSourceRef.value;
  };

  const getDataSourceRef = computed(() => {
    const dataSource = unref(dataSourceRef);
    if (!dataSource || dataSource.length === 0) {
      return unref(dataSourceRef);
    }
    return dataSource;
  });

  async function fetch(option?: { [x: string]: any } | undefined) {
    const { request, pagination }: any = unref(propsRef);

    // 定义分页字段
    const pageField = apiSetting.pageField;
    const sizeField = apiSetting.sizeField;
    const countField = apiSetting.countField;
    const listField = apiSetting.listField;

    // 分页信息
    const { page = defaultPage, pageSize = defaultPageSize } = unref(
      getPaginationInfo
    ) as PaginationProps;

    const params: any = {};

    if (pagination) {
      params[pageField] = (option && option[pageField]) || page;
      params[sizeField] = pageSize;
    }

    console.log('params--->', params);

    // 拉取数据
    const result = await request(params);

    const resultCount = result[countField] || 0;
    const resultPage = result[pageField];

    // 异常处理 ... 后续完善 try

    const resultList = result[listField] ? result[listField] : [];
    dataSourceRef.value = resultList;

    setPagination({
      [pageField]: resultPage,
      [countField]: resultCount,
    });
  }

  onMounted(() => {
    setTimeout(() => {
      fetch();
    }, 0);
  });

  return { getRowKey, getDataSourceRef, getDataSource, setTableData, fetch };
}
